import { AppConfig } from '@/utils/back/appConfig';
import { NextRequest, NextResponse } from 'next/server';
import fs, { ReadStream } from 'fs-extra';
import path from 'path';

async function getConfig(req: NextRequest) {
  let data: null | Obj = {};
  const configFpath = path.join(__dirname, 'config.json');
  if (fs.existsSync(configFpath)) {
    data = JSON.parse(fs.readFileSync(configFpath, 'utf-8'));
  } else {
    data = null;
  }

  // console.log('🚀 ~ getConfig ~ data:', data);
  return NextResponse.json({ success: !!data, message: 'get ok', data });
}

function getJsonFromStream(rs: ReadableStream) {
  const parseData = async (resolve: Fn) => {
    // Create a reader for the stream
    const reader = rs.getReader();
    const decoder = new TextDecoder('utf-8');
    let result = '';
    let done = false;

    // Read the stream until it's done
    while (!done) {
      const { value, done: doneReading } = await reader.read();
      done = doneReading;
      // Decode the chunk and append it to result
      result += decoder.decode(value, { stream: true });
    }

    // Parse the resulting string as JSON
    let data = {};
    try {
      data = JSON.parse(result);
    } catch (err) {
      console.log('🚀 ~ getJsonFromStream ~ err:', err);
    }

    resolve(data);
  };
  return new Promise(parseData);
}

async function saveConfig(req: NextRequest) {
  let data = req.body || {};
  if (data instanceof ReadableStream) {
    data = await getJsonFromStream(data);
  }
  fs.writeFileSync(
    path.join(__dirname, 'config.json'),
    JSON.stringify(data, null, 2)
  );

  // console.log('🚀 ~ saveConfig ~ data:', data);
  return NextResponse.json({ success: true, message: 'save ok', data });
}

export async function GET(req: NextRequest) {
  return await getConfig(req);
}

export async function POST(req: NextRequest) {
  return await saveConfig(req);
}
